<!-- 学校招生人数表维护 -->
<template>
  <section>
    
    <!--新增-->
      <el-form label-position="right" :inline="true" :model="saveForm" ref="saveForm"
               :rules="editFormRules">
        
        <!-- 图片上传组件辅助 -->
        <el-upload
          class="avatar-uploader"
          :action="serverUrl"
          name="file"
          :headers="header"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"

          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="3"
          :on-exceed="handleExceed"
          :file-list="fileList">
        </el-upload>
        <!-- v-model 自动绑定不需要changes去改变 -->
        <quill-editor
          v-model="saveForm.content"
          ref="myQuillEditor"
          :options="editorOption"
          @change="onEditorChange($event)"
        >
        </quill-editor>

        <div style="width: 300px;margin-top: 10px">
          <el-upload
            class=""
            ref="upload"
            :action="serverUrl"
            name="file"
            :on-success="uploadFileSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :file-list="fileList"
            :headers="header"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary" >添加附件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="primary" @click="submitUpload">上传附件</el-button>

          </el-upload>
        </div>
        <el-form-item label="附件列表">
      </el-form-item>
        <div v-for="(file,index) in this.files">
          <a :href="file" v-text="file.split('/')[4]" download=""></a>
        </div>
        <!-- <el-form-item style="display: none">
          <el-input v-model="this.files"></el-input>
        </el-form-item> -->

        
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveDialogVisible = false;">取消</el-button>
        <el-button type="primary" @click.native="saveFormSubmit" :loading="saveFormSubmitLoading">确认</el-button>
      </div>
  </section>
</template>

<script>
  import {api} from '@/api';
  //import {formatDate} from "@/common/date";
  //import utils from "@/common/utils"; //导入工具函数

  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction
    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image'],
    ['clean']

  ]
// https://www.awesomes.cn/repo/surmon-china/vue-quill-editor
  export default {
    data() {
      return {
        fileList: [],
        policyTitle: '',
        list: [],
        token: JSON.parse(sessionStorage.getItem('userInfo')).token,
        listLoading: false,
        page: 1,
        pageSize: 60,
        total: 0,
        viewDialogVisible:false,
        //编辑
        editDialogVisible: false, //是否显示编辑dialog
        editFormSubmitLoading: false, //编辑-提交loading
        saveDialogVisible: false, //是否显示新增dialog
        saveFormSubmitLoading: false, //新增-提交loading
        files:[],
        editForm: {
          id: "",
          attachmentUrl: "",//(string, optional): 附件地址 ,
          content: "",//(string, optional): 文本内容 ,
          issueDate: "",//(string, optional): 发布日期 ,
          sort: "",//(integer, optional): 排序 ,
          title: "",//(string): 标题
        },
        viewForm: {
          id: "",
          attachmentUrl: "",//(string, optional): 附件地址 ,
          content: "",//(string, optional): 文本内容 ,
          issueDate: "",//(string, optional): 发布日期 ,
          sort: "",//(integer, optional): 排序 ,
          title: "",//(string): 标题
        },
        saveForm: {
          attachmentUrl: "",// (string, optional): 附件地址 ,
          content: "",//(string, optional): 文本内容 ,
          issueDate: new Date(),// (string, optional): 发布日期 ,
          sort: "0",//(integer, optional): 排序 ,
          title: "",//(string): 标题
        },
        editFormRules: {//表单验证
          content: [{required: true, message: '必填', trigger: 'blur'}],
          sort: [{required: true, message: '必填', trigger: 'blur'}],
          issueDate: [{required: true, message: '必填', trigger: 'blur',type:'date'}],
          title: [{required: true, message: '必填', trigger: 'blur'}],
        },
        //删除
        deleteLoading: null,
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        editorOption: {
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function (value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        serverUrl: '/ep/admissionsPolicy/upload',  // 这里写你要上传的图片服务器地址
        header: {
          token: JSON.parse(sessionStorage.getItem('userInfo')).token
        } // 有的图片服务器要求请求头需要有token
      }
    },
    methods: {
      //获取列表
      getList: function () {
        this.list = [];
        let params = {
          page: this.page, //当前页为第几页
          limit: this.pageSize, //每页显示多少条
          title: this.policyTitle,
        };

        this.listLoading = true;
        api.infoPublish.enrollmentpolicy.list(params).then(res => {
          let {code, msg, result} = res.data;
          if (code == 0) {
            this.list = result.list;
            this.total = result.totalCount;
          } else {
            this.$message({message: msg, type: 'error'});
          }
          this.listLoading = false;
        });
      },

      //编辑
      handleEdit: function (row) {
        this.files = [];
        this.fileList = [];
        this.editDialogVisible = true; //显示dialog

        this.editForm.id = row.id;
        if (row.attachmentUrl){
          let url = row.attachmentUrl;
          let urls = url.trim().split(",");
          for(let i=0;i<urls.length;i++){
            this.files.push(urls[i]);
          }
          console.log("****** : " + this.files);
        }
        this.editForm.attachmentUrl = row.attachmentUrl;// (string, optional): 附件地址 ,
        this.editForm.content = row.content;//(string, optional): 文本内容 ,
        this.editForm.issueDate =  utils.stringToDate(row.issueDate);// (string, optional): 发布日期 ,
        this.editForm.sort = row.sort + "";//(integer, optional): 排序 ,
        this.editForm.title = row.title;//(string): 标题
      },

      //编辑
      viewEdit: function (row) {
        this.files = [];
        this.fileList = [];
        this.viewDialogVisible = true; //显示dialog

        this.viewForm.id = row.id;
        if (row.attachmentUrl){
          let url = row.attachmentUrl;
          let urls = url.trim().split(",")
          for(let i=0;i<urls.length;i++){
            this.files.push(urls[i]);
          }
          console.log("****** : " + this.files);
        }
        this.viewForm.attachmentUrl = row.attachmentUrl;// (string, optional): 附件地址 ,
        this.viewForm.content = row.content;//(string, optional): 文本内容 ,
        this.viewForm.issueDate =  utils.stringToDate(row.issueDate);// (string, optional): 发布日期 ,
        this.viewForm.sort = row.sort + "";//(integer, optional): 排序 ,
        this.viewForm.title = row.title;//(string): 标题
      },

      edSave: function () {
        this.files = [];
        this.fileList = [];
        this.saveDialogVisible = true;//显示新增dialog
      },

      //新增-提交
      saveFormSubmit: function () {

        let formValid = true;
        this.$refs['saveForm'].validate((valid) => {
          if (!valid) formValid = false;
        });
        if (!formValid) return;
        this.$confirm('确定要提交吗？', '提示', {type: 'info'}).then(() => {
          this.saveFormSubmitLoading = true;

          let params = {
            attachmentUrl: this.files.toString(),// (string, optional): 附件地址 ,
            content: this.saveForm.content,//(string, optional): 文本内容 ,
            issueDate: formatDate(this.saveForm.issueDate, 'yyyy-MM-dd hh:mm:ss'),// (string, optional): 发布日期 ,
            sort: this.saveForm.sort,//(integer, optional): 排序 ,
            title: this.saveForm.title,//(string): 标题

          };

          api.infoPublish.enrollmentpolicy.save(params).then(res => {
            let {code, msg, result} = res.data;
            if (code == 0) {
              this.$message({message: '提交成功', type: 'success'});
              this.saveDialogVisible = false;
              // console.log(this.$refs.myQuillEditor)
              this.$refs.myQuillEditor.quill.root.innerText = '' ;
              this.getList();
            } else {
              this.$message({message: msg, type: 'error'});
            }
          });
        });
      },

      //编辑-提交
      editFormSubmit: function () {
        let formValid = true;
        this.$refs['editForm'].validate((valid) => {
          if (!valid) formValid = false;
        });
        if (!formValid) return;
        this.$confirm('确定要提交吗？', '提示', {type: 'info'}).then(() => {
          this.editFormSubmitLoading = true;

          let params = {
            id: this.editForm.id,//
            attachmentUrl: this.files.toString(),// (string, optional): 附件地址 ,
            content: this.editForm.content,//(string, optional): 文本内容 ,
            issueDate: formatDate(this.editForm.issueDate, 'yyyy-MM-dd hh:mm:ss'),// (string, optional): 发布日期 ,
            sort: this.editForm.sort,//(integer, optional): 排序 ,
            title: this.editForm.title,//(string): 标题
          };

          api.infoPublish.enrollmentpolicy.update(params).then(res => {
            let {code, msg, result} = res.data;
            if (code == 0) {
              this.$message({message: '提交成功', type: 'success'});
              this.editDialogVisible = false;
              this.getList();
            } else {
              this.$message({message: msg, type: 'error'});
            }
          });
        });
      },
      //删除
      handleDelete: function (row) {
        this.$confirm('确定删除该记录吗？', '提示', {type: 'warning'}).then(() => {
          this.deleteLoading = row.id;
          let params = [row.id];
          api.infoPublish.enrollmentpolicy.delete(params).then(res => {
            this.deleteLoading = null;
            let {code, msg, result} = res.data;
            if (code == 0) {
              this.$message({message: '删除成功', type: 'success'});
            } else {
              this.$message({message: msg, type: 'error'});
              return;
            }
            this.getList();
          });
        });
      },
    
   
    
    
      onEditorChange({editor, html, text}) {//内容改变事件
        // console.log("---内容改变事件---")
        // this.content = html
        // console.log(html)
      },
      // 富文本图片上传前
      beforeUpload() {
        console.log('上传图片前')
        // 显示loading动画
        this.quillUpdateImg = true
      },

      uploadSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        console.log(res);
        let quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res.code == 0) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片  res.url为服务器返回的图片地址
          let path = res.msg;
          path=path.replace('\\','/')
          path = '/ep/plugins' + path /*+ "?token=" + JSON.parse(sessionStorage.getItem('userInfo')).token*/;
          quill.insertEmbed(length, 'image', path)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        // loading动画消失
        this.quillUpdateImg = false
      },
      // 富文本图片上传失败
      uploadError() {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')
      },
      // 
      handleRemove(file) {
        console.log(this.files);
        console.log(file);
        for(let i=0;i<this.files.length;i++){
          let tmp = this.files[i];
          console.log(tmp.indexOf(file.name))
          if(this.files[i].indexOf(file.name)!=-1){
            console.log("----: " + file.name)
            this.files.splice(i,1);
          }
        }
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      // 返回true删除
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      // 手动文件上传，upload是定义在upload组件上面的
      submitUpload() {
        this.$refs.upload.submit();
      },
      uploadFileSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        console.log('上传文件')
        console.log(res);
        console.log(file);
        // 如果上传成功
        if (res.code == 0) {
          // 获取光标所在位置

          let path = res.msg;
          path=path.replace('\\','/')
          path = '/ep/plugins' + path ;
          this.files.push(path)
          console.log(this.files);
        } else {
          this.$message.error('文件上传失败')
        }

      },
      fn(event){
        console.log(event.currentTarget.previousElementSibling.innerHTML);
        let name = event.currentTarget.previousElementSibling.innerHTML;
        for(let i=0;i<this.files.length;i++){
          let tmp = this.files[i];
          console.log(tmp.indexOf(name))
          if(this.files[i].indexOf(name)!=-1){
            console.log("----: " + name)
            this.files.splice(i,1);
          }
        }
      },
      dateFormate(row, column, cellValue, index){
        let date = row[column.property]
        if(date){
          date = date.split(" ");
        }
        return date[0];
      }

    }
  }

</script>


<style>
  .ql-editor.ql-blank, .ql-editor {
    width: 100%;
    height: 350px;
  }
</style>
